import * as React from 'react';

import { StyleSheet, View, Text, NativeEventEmitter } from 'react-native';
import TMobileIM, { MobileIM } from 'react-native-mobile-im';

export default function App() {
  React.useEffect(() => {
    const emitter = new NativeEventEmitter(MobileIM);
    const subA = emitter.addListener(TMobileIM.ON_LOGIN_RESPONSE, (data) => {
      console.log(TMobileIM.ON_LOGIN_RESPONSE, JSON.stringify(data));
    });

    const subB = emitter.addListener(TMobileIM.ON_LINK_CLOSE, (data) => {
      console.log(TMobileIM.ON_LINK_CLOSE, JSON.stringify(data));
    });

    const subC = emitter.addListener(TMobileIM.ON_KICK_OUT, (data) => {
      console.log(TMobileIM.ON_KICK_OUT, JSON.stringify(data));
    });

    const subD = emitter.addListener(TMobileIM.ON_RECEIVE_MESSAGE, (data) => {
      console.log(TMobileIM.ON_RECEIVE_MESSAGE, JSON.stringify(data));
    });

    const subE = emitter.addListener(TMobileIM.ON_ERROR_RESPONSE, (data) => {
      console.log(TMobileIM.ON_ERROR_RESPONSE, JSON.stringify(data));
    });

    const subF = emitter.addListener(TMobileIM.MESSAGES_LOST, (data) => {
      console.log(TMobileIM.MESSAGES_LOST, JSON.stringify(data));
    });

    const subG = emitter.addListener(TMobileIM.MESSAGES_BE_RECEIVED, (data) => {
      console.log(TMobileIM.MESSAGES_BE_RECEIVED, JSON.stringify(data));
    });

    return () => {
      subA.remove();
      subB.remove();
      subC.remove();
      subD.remove();
      subE.remove();
      subF.remove();
      subG.remove();
    };
  }, []);

  const login = async () => {
    await TMobileIM.init('schedule.ourtramy.com', 8901);
    const code = await TMobileIM.login(
      '1413150911882199040',
      'MTQxMzE1MDkxMTg4MjE5OTA0MA=='
    );
    if (code !== 0) {
      console.log('数据发送失败，应该进行取消加载类的操作');
    }
  };

  const logout = () => {
    const code = TMobileIM.logout();
    console.log('退出登录：' + code);
  };

  const send = () => {
    const code = TMobileIM.send(
      'test1',
      'wan',
      'slkdfjsljdflsdjkfksdjflsdkjf',
      1
    );
    console.log('发送消息：' + code);
  };

  return (
    <View style={styles.container}>
      <Text onPress={login}>登录</Text>
      <Text onPress={logout}>退出</Text>
      <Text onPress={send}>发送</Text>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
  },
  box: {
    width: 60,
    height: 60,
    marginVertical: 20,
  },
});
